package org.sa.hb;

import java.util.ArrayList;
import java.util.Random;

import org.sa.BPMObserver;
import org.sa.BeatObserver;

public class HeartModel implements HeartModelInterface, Runnable{


	ArrayList<BeatObserver> beatObservers = new ArrayList<BeatObserver>() ;
	ArrayList<BPMObserver> bpmObservers = new ArrayList<BPMObserver>();
	
	int heartrate = 80 ; 
	
	Thread thread ; 

	HeartModel() {
		thread = new Thread(this);		
		thread.start();
	}
	
	@Override
	public int getHeartRate() {
		// TODO Auto-generated method stub
		return heartrate;
	}

	@Override
	public void registerObserver(BeatObserver observer) {
		this.beatObservers.add(observer);		
	}
	
	@Override
	public void registerObserver(BPMObserver observer) {
		this.bpmObservers.add(observer);
	}

	
	@Override
	public void removeObserver(BeatObserver observer) {
		this.beatObservers.remove(observer);		
	}
	@Override
	public void removeObserver(BPMObserver observer) {
		this.bpmObservers.remove(observer);		
	}
	
	private void notifyObservers() {
		 for (BPMObserver bpmO : this.bpmObservers )
		        bpmO.updateBPM()  ;
		 for (BeatObserver beatO : this.beatObservers )
			 beatO.updateBeat(); 
		 
	}

	@Override

	public void run() {
		Random ran = new Random(); 
		for(;;) {
			notifyObservers(); 
			
			int value = this.getHeartRate() ;			
			heartrate = value + (  ran.nextInt(4)  - 2 );
			if ( heartrate < 0 ) heartrate = 0 ; 
			if ( heartrate > 250 ) heartrate = 250 ; 

			try {
				Thread.sleep(1000);
			} catch (Exception e) {};
		}
	}



}
